#include "contactloadthread.h"
#include <QContactManager>
#include <QContactFilter>
#include <QContactPhoneNumber>
#include <QContactName>
#include <QContactDetailFilter>
#include <QContactThumbnail>
#include <QString>
#include <QList>
#include <QThread>
#include <QObject>
#include "dbrecord.h"

//#include <QTime>
//#include <QDebug>

QContactManager * ContactLoadThread::m_manager = 0;

ContactLoadThread::ContactLoadThread( QObject * parent ):
	m_record( 0 ), QThread( parent )
{
	m_contact = 0;
	if ( ! m_manager )
	{
		QStringList list = QContactManager::availableManagers();

		// The resulting QStringList on my N900 contains ("maemo5", "memory", "invalid").
		// Don't know what 'memory' is for or whether this one is ever used or not.
		if ( ! list.isEmpty() )
		{
			m_manager = new QContactManager( list.first() );
		}
		else
		{
			// Try to load the default manager
			m_manager = new QContactManager();
		}
	}
}

ContactLoadThread::~ContactLoadThread()
{
	delete m_contact;
}

void ContactLoadThread::run()
{
	if ( m_record )
	{
		QTime t;
		t.start();

		QContactFilter filter = QContactPhoneNumber::match( m_record->phoneNumber() );
		QList< QContact > matches = m_manager->contacts( filter );
//		qDebug() << m_record->name() << " has " << matches.count() << " matches";
		if ( matches.size() != 0 )
		{
			m_contact = new QContact;
			* m_contact = matches.at( 0 );
		}
	//	qDebug() << "Load contact " << m_record->name() << ", time elapsed: " << t.elapsed() << " ms";
	}
}

void ContactLoadThread::setDbRecord( const DBRecord * rec )
{
	m_record = rec;
	delete m_contact;
	m_contact = 0;
}
